/*===========================================================================
  Copyright (C) 2014 by the Okapi Framework contributors
-----------------------------------------------------------------------------
  This library is free software; you can redistribute it and/or modify it 
  under the terms of the GNU Lesser General Public License as published by 
  the Free Software Foundation; either version 2.1 of the License, or (at 
  your option) any later version.

  This library is distributed in the hope that it will be useful, but 
  WITHOUT ANY WARRANTY; without even the implied warranty of 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
  General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License 
  along with this library; if not, write to the Free Software Foundation, 
  Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

  See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/

package net.sf.okapi.lib.omegat;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;

public class XLIFFDetector {

	/**
	 * Gets the version of an XLIFF document.
	 * @param inputFile the file to inspect.
	 * @return the version of the xliff element.
	 * @throws XMLStreamException if an XML reading error occurred.
	 * @throws IOException if no version could be detected or an error occurred.
	 */
	public static String getXLIFFVersion (File inputFile)
		throws XMLStreamException, IOException
	{
		XMLStreamReader reader = null;
		XMLInputFactory factory = XMLInputFactory.newFactory();
		try {
			reader = factory.createXMLStreamReader(new FileInputStream(inputFile));
			while ( reader.hasNext() ) {
				switch ( reader.next() ) {
				case XMLEvent.START_ELEMENT:
					if ( reader.getName().getLocalPart().equals("xliff") ) {
						String version = reader.getAttributeValue("", "version");
						if ( version == null ) {
							throw new IOException("The version attribute is missing.");
						}
						return version;
					}
					// Else: not an XLIFF document
					throw new IOException("No <xliff> element found.");
				}
			}
		}
		finally {
			if ( reader != null ) reader.close();
		}
		
		// Should not get here
		throw new IOException("No element in the file.");
	}

}
